﻿namespace BadHabit.Factory.Windows
{
    using System;
    using System.Collections.Specialized;
    using System.Web;
    using Microsoft.VisualBasic.ApplicationServices;

    /// <summary>
    /// The entry point to make it a singleton.
    /// </summary>
    public class SingletonEntryPoint
    {
        [STAThread]
        public static void Main(string[] args)
        {
            string[] newArgs = new string[3];
            
            NameValueCollection parameters = GetQueryStringParameters();

            // ServerUrl Parameter
            if (!String.IsNullOrEmpty(parameters["ServerUrl"]))
            {
                newArgs[0] = parameters["ServerUrl"];
            }
            else
            {
                newArgs[0] = "DEFAULT";
            }

            // ProjectNumber parameter            
            if (!String.IsNullOrEmpty(parameters["ProjectNumber"]))
            {
                newArgs[1] = parameters["ProjectNumber"];
            }
            else
            {
                newArgs[1] = "-1";
            }

            if (!String.IsNullOrEmpty(parameters["TaskId"]))
            {
                newArgs[2] = parameters["TaskId"];
            }
            else
            {
                newArgs[2] = "-1";
            }

            SingleInstanceManager manager = new SingleInstanceManager();

            manager.Run(newArgs);
        }

        public static NameValueCollection GetQueryStringParameters()
        {
            if (AppDomain.CurrentDomain.SetupInformation.ActivationArguments == null)
            {
                return new NameValueCollection();
            }

            if (AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData == null)
            {
                return new NameValueCollection();
            }

            string url = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData[0];
            if (url.IndexOf('?') >= 0)
            {
                return HttpUtility.ParseQueryString(url.Substring(url.IndexOf('?')));
            }

            return new NameValueCollection();
        }
    }

    // Using VB bits to detect single instances and process accordingly:
    //  * OnStartup is fired when the first instance loads
    //  * OnStartupNextInstance is fired when the application is re-run again
    //    NOTE: it is redirected to this instance thanks to IsSingleInstance
    public class SingleInstanceManager : WindowsFormsApplicationBase
    {
        private BadHabit.Factory.Client app;

        public SingleInstanceManager()
        {
            this.IsSingleInstance = true;
        }

        /// <summary>
        /// On startup create the Factory application and runs it.
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
        {
            // First time app is launched
            this.app = new BadHabit.Factory.Client();

            try
            {
                this.app.Run();
            }
            catch (Exception ex)
            {
                Views.Error.ShowError(ex, "Unexpected Error");
            }

            return false;
        }

        /// <summary>
        /// On next instance, activate the old instance.
        /// </summary>
        /// <param name="eventArgs"></param>
        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e)
        {
            base.OnStartupNextInstance(e);
            
            this.CallActivate(e.CommandLine);
        }

        private void CallActivate(System.Collections.ObjectModel.ReadOnlyCollection<string> args)
        {
            // if parameter 1 was informed (ServerUrl)
            if (args.Count > 0)
            {
                if (!args[0].Equals("DEFAULT"))
                {
                    global::BadHabit.Factory.Windows.Properties.Settings.Default.ProjectWebServiceURL = args[0];
                    Client.SetUpService();
                }
            }

            // if parameter 2 was informed (ProjectNumber)
            if (args.Count > 1)
            {
                int projectNumber = -1;
                if (Int32.TryParse(args[1], out projectNumber))
                {
                    if (projectNumber > 0)
                    {
                        Client.ShowMainWindow(projectNumber);
                        return;
                    }
                }
            }

            if (args.Count > 2)
            {
                int taskId = -1;
                if (Int32.TryParse(args[2], out taskId))
                {
                    if (taskId > 0)
                    {
                        Views.TaskDetail w = new Views.TaskDetail(taskId);
                        w.Show();
                        return;
                    }
                }
            }

            Client.ShowMainWindow();
        }
    }
}